<template>
    <div class="user-edit all-height">
        <!-- Drawer抽屉 -->
        <!-- <Drawer
        :title="title"
        v-model="visible"
        width="720"
        draggable
        :mask-closable="type == '0'"
    > -->
        <div :style="{ maxHeight: maxHeight }" class="drawer-content all-height">
            <div class="drawer-header">
                <div class="cmr16"  v-show="type == '2'">添加区</div>
                <div class="cmr16" v-show="type != '2'">编辑区</div>
                <!-- <Avatar :src="form.avatar" size="large" v-show="type != '2'"/> -->
            </div>
            <Form label-colon v-show="type != '2'" label-position="right" :label-width="labelWidth">
                <Row :gutter="32">
                    <!--            <Col span="24">-->
                    <!--              <FormItem label="用户ID">-->
                    <!--                {{ form.id }}-->
                    <!--                <Tooltip trigger="hover" placement="right" content="账户已禁用">-->
                    <!--                  <Icon-->
                    <!--                      v-show="form.status == -1"-->
                    <!--                      type="md-lock"-->
                    <!--                      size="18"-->
                    <!--                      style="margin-left: 10px; cursor: pointer"-->
                    <!--                  />-->
                    <!--                </Tooltip>-->
                    <!--              </FormItem>-->
                    <!--            </Col>-->
                    <Col span="24">
                        <FormItem label="账号">
                            {{ form.username }}
                            <Tooltip trigger="hover" placement="right" content="账户已禁用">
                                <Icon v-show="form.status == -1" type="md-lock" size="18" 
                                class='cml10' style="cursor: pointer" />
                            </Tooltip>
                        </FormItem>
                    </Col>
                </Row>
            </Form>
            <Form ref="form" :model="form" :rules="formValidate" label-position="right" :label-width="labelWidth">
                <Row :gutter="32" v-if="type == '2'">
                    <Col span="24">
                        <FormItem label="账号" prop="username" style="position: relative" key="1">
                            <Input v-model="form.username" autocomplete="off" maxlength="16" placeholder="学校代码+院系代码" />
                            <!--              <input type="text" name="username" style="position: fixed;z-index: -10000;width: 0;border: none"></input>-->
                        </FormItem>
                    </Col>
                    <Col span="24">
                        <FormItem label="密码" prop="password" key="2">
                            <SetPassword v-model="form.password" @on-change="changePass" />
                        </FormItem>
                    </Col>
                </Row>
                <Row :gutter="32">
                    <Col span="24">
                        <FormItem label="姓名" prop="name" key="3">
                            <Input v-model="form.name" maxlength="20" />
                        </FormItem>
                    </Col>
                    <!--            <Col span="24">-->
                    <!--              <FormItem label="所在高校" prop="gxcode" >-->
                    <!--                <Select v-model="form.gxcode" clearable>-->
                    <!--                  <Option value="0">请自行编辑下拉菜单</Option>-->
                    <!--                </Select>-->
                    <!--              </FormItem>-->
                    <!--            </Col>-->
                    <Col span="24">
                        <FormItem label="管理院系" prop="yxcode" key="4">
                            <Select v-model="form.yxcode" filterable multiple label-in-value @on-change="handleChange">
                                <checkbox v-model="yxcodeAll" @on-change="yxcodeClickAll">全选</checkbox>
                                <Option v-for="item in yxList" :value="item.yxcode" :key="item.id">{{ item.yxname }}</Option>
                            </Select>
                        </FormItem>
                    </Col>
                </Row>
                <Row :gutter="32">
                    <!--            <Col span="24">-->
                    <!--              <FormItem label="所属部门" class="form-noheight">-->
                    <!--                <department-tree-choose-->
                    <!--                    @on-change="handleSelectDepTree"-->
                    <!--                    ref="depTree"-->
                    <!--                ></department-tree-choose>-->
                    <!--              </FormItem>-->
                    <!--            </Col>-->
                </Row>
                <Row :gutter="32">
                    <Col span="24">
                        <FormItem label="角色" prop="roleIds" key="5">
                            <Select v-model="form.roleIds" multiple transfer max-tag-count="1" placeholder = "默认院系管理员">
                                <Checkbox @on-change="roleIdsClickAll" v-model="roleIdsAll">全选</Checkbox>
                                <Option v-for="item in roleList" :value="item.id" :key="item.id" :label="item.description">
                                    <span style="margin-right: 10px">{{ item.name }}</span>
                                    <span style="color: #ccc">{{ item.description }}</span>
                                </Option>
                            </Select>
                        </FormItem>
                    </Col>
                    <Col span="24">
                        <FormItem label="管理的学历层次" prop="glxlcc" key="6">
                            <Select v-model="form.glxlcc" filterable multiple>
                                <checkbox v-model="glxlccChecked" @on-change="selectGlxlccAllOptions">全选</checkbox>
                                <Option v-for="item in glxlccList" :value="item.value" :key="item.id">{{ item.title }}</Option>
                            </Select>
                        </FormItem>
                    </Col>
                </Row>
                <Row :gutter="32">
                    <Col span="24">
                        <FormItem label="职务" prop="zw">
                            <Input v-model="form.zw" clearable maxlength="20" />
                        </FormItem>
                    </Col>
                    <Col span="24">
                        <FormItem label="电话" prop="telephone">
                            <Input v-model="form.telephone" clearable maxlength="20" />
                        </FormItem>
                    </Col>
                </Row>
                <Row :gutter="32">
                    <Col span="24">
                        <FormItem label="手机号" prop="mobile">
                            <Input v-model="form.mobile" maxlength="20" />
                        </FormItem>
                    </Col>
                    <Col span="24">
                        <FormItem label="传真" prop="fax">
                            <Input v-model="form.fax" clearable maxlength="20" />
                        </FormItem>
                    </Col>
                </Row>

                <Row :gutter="32">
                    <Col span="24">
                        <FormItem label="邮箱">
                            <Input v-model="form.email" transfer maxlength="20" />
                        </FormItem>
                    </Col>
                    <Col span="24">
                        <FormItem label="QQ" prop="qq">
                            <Input v-model="form.qq" clearable maxlength="20" />
                        </FormItem>
                    </Col>
                </Row>
                <Row :gutter="32">
                    <Col span="24">
                        <FormItem label="排序值" prop="sortOrder">
                            <Tooltip trigger="hover" placement="right" content="值越小越靠前，支持小数">
                                <Input v-model="form.sortorder" clearable />
                            </Tooltip>
                        </FormItem>
                    </Col>
                </Row>
            </Form>
        </div>
        <div class="br right-bottom-edit">
            <Button type="text" @click="cancel">取消</Button>

            <div v-if="type == '1'" style="display: inline">
                <Button v-has="'edit'" type="primary" :loading="submitLoading" @click="submit">提交</Button>
            </div>
            <div v-if="type == '2'" style="display: inline">
                <Button v-has="'add'" type="primary" :loading="submitLoading" @click="submit">提交</Button>
            </div>
        </div>
        <!-- </Drawer> -->
    </div>
</template>

<script>
import { addCollegePersonInfo, editCollegePersonInfo } from '@/api/bys/personInfo/college.js';
import { getAllYxManageList } from '@/api/bys/yx/yx.js';
import { getRoles as getRoleList, getAllDictDataList } from '@/api/index';
import { validateUsername, validateMobileNoBt, validatePassword } from '@/libs/validate';
import departmentTreeChoose from '@/views/my-components/xboot/department-tree-choose';
import uploadPicInput from '@/views/my-components/xboot/upload-pic-input';
import SetPassword from '@/views/my-components/xboot/set-password';
import dict from '@/views/my-components/xboot/dict';
import { getDictDataByType } from '@/api/index.js';
import Cookies from 'js-cookie';

export default {
    name: 'user',
    components: {
        departmentTreeChoose,
        uploadPicInput,
        SetPassword,
        dict
    },
    props: {
        value: {
            type: Boolean,
            default: false
        },
        data: {
            type: Object
        },
        type: {
            type: String,
            default: '0'
        }
    },
    data() {
        const validateyxcode = (rule, value, callback) => {
           if(this.form.yxcode !== '' && this.form.yxcode !== null && this.form.yxcode){
               callback();
           }else{
               callback(new Error('请选择管理院系'));
           }
        };
        const validateroleIds = (rule, value, callback) => {
            if(this.form.roleIds !== '' && this.form.roleIds !== null && this.form.roleIds){
                callback();
            }else{
                callback(new Error('请选择角色'));
            }
        };
        const validateglxlcc = (rule, value, callback) => {
            if(this.form.glxlcc !== '' && this.form.glxlcc !== null && this.form.glxlcc){
                callback();
            }else{
                callback(new Error('请选择管理的学历层次'));
            }
        };
        return {
            labelWidth: 110,
            glxlccChecked: false,
            roleIdsAll: false, //角色全选
            yxcodeAll: false, //管理全选
            switchStatus: true,
            yxList: [],
            glxlccList: [],
            roleList: [],
            visible: this.value,
            title: '',
            passColor: '',
            submitLoading: false,
            maxHeight: 510,
            form: {
                username: '',
                name: '',
                yxcode: '',
                roleIds: '',
                glxlcc: '',
                password: '',
                mobile: '',
                email: '',
                type: 0,
                address: []
            },
            formValidate: {
                // 表单验证规则
                username: [
                    { required: true, message: '请输入账号', trigger: 'change' },
                    { validator: validateUsername, trigger: 'change' }
                ],
                name: [{ required: true, message: '请输入姓名', trigger: 'change' }],
                yxcode: [{  validator: validateyxcode,  required: true, trigger:  'change' }],
                roleIds: [{ validator: validateroleIds, required: true, trigger:  'change' }],
                glxlcc: [{ validator: validateglxlcc, required: true, trigger:  'change' }],
                password: [
                    { required: true, message: '请输入密码', trigger: 'blur' },
                    { validator: validatePassword, trigger: 'blur' }
                ],
                mobile: [
                    // {required: true, message: "请输入手机号", trigger: "change"},
                    { validator: validateMobileNoBt, trigger: 'change' }
                ],
                email: [
                    // {required: true, message: "请输入邮箱地址"},
                    { type: 'email', message: '邮箱格式不正确' }
                ]
            }
        };
    },
    methods: {
        init() {
            this.getRoleList();
            this.getAllYxList();
            this.getGlxlccDictList();
        },
        // addSelectAll(){
        //   this.roleIdsAll=true
        //   this.yxcodeAll=true
        //   this.roleIdsClickAll()
        //   this.yxcodeClickAll()
        // },
        // 角色全选
        roleIdsClickAll() {
            if (this.roleIdsAll) {
                this.form.roleIds = this.roleList.map(option => option.id);
            } else {
                this.form.roleIds = [];
            }
        },
        // 管理院系
        yxcodeClickAll(e) {
            this.yxcodeAll = e;
            if (this.yxcodeAll) {
                this.form.yxcode = this.yxList.map(option => option.yxcode);
                this.form.yxname = this.yxList.map(option => option.yxname);
            } else {
                this.form.yxcode = [];
                this.form.yxname = [];
            }
        },
        handleChange(e) {
            this.form.yxcode = e.map((item, index, arr) => {
                return item.value;
            });
            this.form.yxname = e.map((item, index, arr) => {
                return item.label;
            });
            console.log(this.form.yxcode, 'yxcode');
            console.log(this.form.yxname, 'yxname');
        },
        getAllYxList() {
            let resource = JSON.parse(Cookies.get('userInfo')).resource;
            if ( resource == 1){
                return
            }
            getAllYxManageList().then(res => {
                if (res.success) {
                    if (res.result.length == 0) {
                        this.$alert('当前暂无院系信息，请到“学校管理-院系信息”处添加院系信息', '提示', {
                            confirmButtonText: '确定'
                        });
                    }
                    console.log(res.result, '他天涯必须');
                    this.yxList = res.result;
                }
            });
        },
        getRoleList() {
            let role=[
                {
                    description: "高校管理员",
                    id:"1693900166597316609",
                    name:"ROLE_SCHOOL"
                },
                {
                    description: "院系管理员",
                    id:"1693900223967006720",
                    name:"ROLE_COLLEGE"
                },
            ]
            let role1=[
                {
                    description: "就业信息管理员",
                    id:"1693909116419969025",
                    name:"ROLE_JIUYE"
                },
                {
                    description: "困难帮扶管理员",
                    id:"1733854359604826112",
                    name:"ROLE_HARD"
                },
                {
                    description: "户口信息管理员",
                    id:"1693908997037494273",
                    name:"ROLE_HUKOU"
                },
                {
                    description: "档案信息管理员",
                    id:"1693908732192362497",
                    name:"ROLE_DANGAN"
                },
                {
                    description: "招聘信息管理员",
                    id:"1766364358260166656",
                    name:"ROLE_RECRUIT"
                },
            ]
            getRoleList({ level: 'college' }).then(res => {
                if (res.success) {
                    this.roleList = res.result;
                    console.log("角色",res)
                    // 学校添加的时候，暂定只能添加高校和院系这两个角色
                    this.roleList=role1
                }
            });
        },

        getGlxlccDictList() {
            // 学历层次
            getDictDataByType('eduLevelType').then(res => {
                if (res.success) {
                    this.glxlccList = res.result;
                }
            });
        },
        // handleSelectDepTree(v) {
        // this.form.departmentid = v;
        // this.form.departmenttitle = this.$refs.depTree.departmentTitle;
        // },
        changePass(v, grade, strength) {
            this.form.passStrength = strength;
            this.form.password = v;
            // this.$refs.form.validateField('password');
        },
        submit() {
            console.log(this.form)
            this.$refs.form.validate(valid => {
                if (valid) {
                    if (typeof this.form.birth == 'object') {
                        this.form.birth = this.format(this.form.birth, 'yyyy-MM-dd');
                    }
                    if (this.type == '1') {
                        // 默认添加院系管理员
                        let roleIds=["1693900223967006720"]
                        roleIds.push(this.form.roleIds)
                        // 编辑
                        this.submitLoading = true;
                        editCollegePersonInfo({ ...this.form,roleIds:roleIds }).then(res => {
                            this.submitLoading = false;
                            if (res.success) {
                                this.$Message.success('操作成功');
                                this.$emit('on-submit', true);
                                this.visible = false;
                                this.cancel();
                            }
                        });
                    } else {
                        // 默认添加院系管理员
                        let roleIds=["1693900223967006720"]
                        roleIds.push(this.form.roleIds)
                        // 添加
                        this.submitLoading = true;
                        console.log(this.form, 'kkk');
                        console.log(roleIds, 'kkk');
                        addCollegePersonInfo({ ...this.form,roleIds:roleIds }).then(res => {
                            this.submitLoading = false;
                            if (res.success) {
                                this.$Message.success('操作成功');
                                this.$emit('on-submit', true);
                                this.visible = false;
                                this.cancel();
                            }
                        });
                    }
                }
            });
        },
        cancel() {
            this.$emit('open-search', true);
            this.form = [];
        },
        setCurrentValue(value) {
            if (value === this.visible) {
                return;
            }
            if (this.type == '1') {
                this.title = '编辑用户';
                this.maxHeight = Number(document.documentElement.clientHeight - 121) + 'px';
            } else if (this.type == '2') {
                this.title = '添加用户';
                this.maxHeight = Number(document.documentElement.clientHeight - 121) + 'px';
            } else {
                this.title = '用户详情';
                this.maxHeight = '100%';
            }
            // 清空数据
            this.$refs.form.resetFields();
            if (this.type == '0' || this.type == '1') {
                // 回显数据
                let data = this.data;
                // 部门
                // this.$refs.depTree.setData(data.departmentid, data.departmenttitle);
                // 角色
                let selectRolesId = [];
                if (data.roles) {
                    data.roles.forEach(function (e) {
                        selectRolesId.push(e.id);
                    });
                }
                if (data.yxcode) {
                    data.yxcode = data.yxcode.split(',');
                }
                data.roleIds = selectRolesId;
                delete data.roles;
                delete data.permissions;
                // 密码强度
                if (data.passStrength == '弱') {
                    this.passColor = '#ed3f14';
                } else if (data.passStrength == '中') {
                    this.passColor = '#faad14';
                } else if (data.passStrength == '强') {
                    this.passColor = '#52c41a';
                }
                // 回显
                this.form = data;
                if (this.form.glxlcc) {
                    this.form.glxlcc = this.form.glxlcc.split(',');
                } else {
                    this.form.glxlcc = [];
                }
                console.log(this.form.glxlcc, '学历层次');
            } else {
                // // 添加
                // this.$refs.depTree.setData("", "");
                // this.form = {
                //   type: 0,
                //   sex: "",
                //   address: [],
                // };
            }
            this.visible = value;
        },
        // 生成假手机号
        getMockMobile() {
            const mobilePrefix = '152';
            let mobileSuffix = '';
            for (let i = 0; i < 8; i++) {
                mobileSuffix += Math.floor(Math.random() * 10);
            }
            // console.log(mobilePrefix + mobileSuffix);
            return mobilePrefix + mobileSuffix;
        },
        selectGlxlccAllOptions() {
            if (this.glxlccChecked) {
                this.form.glxlcc = this.glxlccList.map(item => item.value);
            } else {
                this.form.glxlcc = '';
            }
        },
        onRestWindow() {
            this.labelWidth = this.searchLabelWidth(this.labelWidth)
        }
    },
    watch: {
        data(val) {
            this.setCurrentValue(val);
        },
        visible(value) {
            // if(value){
            //   this.form={}
            // }
            this.$emit('input', value);
        },
        form: {
            deep: true,
            handler() {
                if (this.form.glxlcc.length === this.glxlccList.map(item => item.value).length) {
                    this.glxlccChecked = true;
                } else {
                    this.glxlccChecked = false;
                }
            }
        },
        
    },
    mounted() {
        this.onRestWindow()
        window.addEventListener('resize',this.onRestWindow)
        this.init();
    },
    beforeDestroy() {
        window.removeEventListener('resize',this.onRestWindow)
    },
    created() {}
};
</script>

<style lang="less">
@import '../../../styles/drawer-common.less';
@import '../../personInfo.less';

.ivu-form-item {
    margin-bottom: 0.1rem;
}

.ivu-input-prefix {
    top: 0.03rem;
}
.cmr16 {
    margin-right: 16px;
}
.cml10 {
    margin-left: 10px; 
}
</style>
<style lang="less" scoped>
// 重构样式
/deep/ .ivu-form-item-label{
    display: flex;
    justify-content: right;
    width: 150px !important;
}
/deep/ .ivu-form-item {
    width: 100%;
    margin-bottom: 0.1rem;
    margin-right: 0 !important;
    display: flex;
    align-items: center;
    justify-content: space-between;
}
/deep/ .ivu-form-item-content {
    width: 100% !important;
    margin-left: 0 ! important;
}
/deep/ .ivu-select {
    width: 100% !important;
}
/deep/ .ivu-date-picker {
    width: 100% !important;
}
/deep/ .br {
    margin-top: 15px;
    bottom: 0.12rem !important;
    .ivu-form-item-content {
        display: flex;
    }
}
/deep/ .ivu-input-type-textarea,/deep/ .ivu-input {
    height: calc(100% - 7px) !important;
}
.flex-1 {
    height: 100%;
}
/deep/ .ivu-drawer-body {
    overflow: hidden;
    .d-flex-align-center {
        height: fit-content !important;
        margin-left: 0 !important;
        justify-content: right;
        box-sizing: border-box;
        padding-right: 7px;
    }
}
.box-key {
    /deep/ .ivu-form-item-content {
        margin-left: 100px !important;
    }
}
/deep/ .ivu-tooltip {
    width: 100%;
}
</style>
